package com.gxd.fastdfs.web;

import com.gxd.commons.base.BaseController;
import com.gxd.commons.model.CommonResult;
import com.gxd.commons.model.Result;
import com.gxd.commons.utils.FtpUtils;
import com.gxd.commons.utils.SFTPUtils;
import com.gxd.commons.utils.StringUtils;
import com.gxd.fastdfs.config.SFTPConfigProperties;
import com.jcraft.jsch.JSchException;
import fastdfs.client.FastdfsClient;
import fastdfs.client.FileId;
import fastdfs.client.TrackerServer;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Author:gxd
 * @Description:
 * @Date: 12:10 2018/8/18
 * @Modified By:
 */
@SuppressWarnings("SpringJavaAutowiringInspection") //加这个注解让IDE 不报: Could not autowire
@Controller
@RequestMapping("/file")
public class UploadController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired(required = false)
    private SFTPConfigProperties sftpConfigProperties;

    @Value("${fastdfs.webServerUrl}")
    private String webServerUrl;
    @Value("${fastdfs.tracker_servers}")
    private  String trackerServers;
    @Value("${fastdfs.connectTimeout}")
    private  int connectTimeout;
    @Value("${fastdfs.readTimeout}")
    private  int readTimeout;
    @Value("${fastdfs.maxThreads}")
    private  int maxThreads;
    private FastdfsClient client;
    @RequestMapping(value = "/toupload", method = RequestMethod.GET)
    private String toUpload(){
        return "view/upload";
    }

    @PostConstruct
    public void init() throws Exception {
        client = FastdfsClient.newBuilder()
                .connectTimeout(connectTimeout)
                .readTimeout(readTimeout)
                .maxThreads(maxThreads)
                .trackers(getTrackers())
                .build();
    }


    /**
     * 访问路径为：http://ip:port/file/fileupload
     * @return
     */
    @RequestMapping(value = "/fileupload1", method = RequestMethod.GET)
    public String upload() {
        return "view/fileupload1";
    }

    @RequestMapping(value = "/fileupload2", method = RequestMethod.GET)
    public String upload2() {
        return "view/fileupload2";
    }

    @RequestMapping(value = "/fileThumb", method = RequestMethod.GET)
    public String fileThumb() {
        return "view/fileThumb";
    }

    /**
     * 访问路径为：http://ip:port/file/mutifileupload
     * @return
     */
    @RequestMapping(value = "/filebatchupload", method = RequestMethod.GET)
    public String batchUpload() {
        return "view/filebatchupload";
    }

    /**
     * 读取ftp路径并上传fastdfs
     * @return
     */
    @RequestMapping(value = "/ftpfileupload", method = RequestMethod.GET)
    private String ftpToUpload(){
        return "view/ftpfileupload";
    }
    @RequestMapping(value = "/filedownload", method = RequestMethod.GET)
    public String filedownload() {
        return "view/download";
    }

    /**
     * 读取sftp路径并上传fastdfs
     * @return
     */
    @RequestMapping(value = "/sftpfileupload", method = RequestMethod.GET)
    private String sftpToUpload(){
        return "view/sftpfileupload";
    }

    private List<TrackerServer> getTrackers(){
        List<TrackerServer> list = new ArrayList();
        String spr1 = ",";
        String spr2 = ":";
        String[] arrs = trackerServers.trim().split(spr1);
        String[] var = arrs;
        int len = arrs.length;
        for(int i = 0; i < len; ++i) {
            String addrStr = var[i];
            String[] address = addrStr.trim().split(spr2);
            String host = address[0].trim();
            int port = Integer.parseInt(address[1].trim());
            list.add(new TrackerServer(host, port));
        }
        return list;
    }
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> upload(MultipartHttpServletRequest multipartFile, HttpServletRequest request){
        Map<String,String> result = new HashMap<String,String>(16);
        //参数名称
        String param = request.getParameter("param");
        if(StringUtils.isEmpty(param)){
            result.put("result","false");
            result.put("msg","请添加参数");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        InputStream inputStream  = null;
        String fileName = "";
        String path = "";
        try {
            MultipartFile file = multipartFile.getFile(param);
            fileName = file.getOriginalFilename();
            byte[] fileBuff = null;
            inputStream = file.getInputStream();
            if(inputStream!=null){
                int len1 = inputStream.available();
                fileBuff = new byte[len1];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            path = webServerUrl+res.get().toString();
            logger.debug("upload上传成功，路径："+path);
        }catch (Exception e){
            result.put("result","false");
            logger.error("file:"+fileName,e.fillInStackTrace());
            result.put("msg","上传失败");
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            return  result;
        }  finally {
            if (inputStream !=null){
                try {
                    inputStream.close();
                }catch (IOException io){
                    logger.error(io.getMessage());
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    result.put("result","false");
                    result.put("msg","上传失败");
                    return result;
                }
            }
        }
        result.put("result","true");
        //图片地址
        result.put("srckey",path);
        result.put("msg","上传成功");
        response.setStatus(HttpServletResponse.SC_OK);
        return result;
    }

    @RequestMapping(value = "/v2/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult uploadV2(MultipartHttpServletRequest multipartFile, HttpServletRequest request,HttpServletResponse response){
        CommonResult result = new CommonResult();
        //参数名称
        String param = request.getParameter("param");
        if(StringUtils.isEmpty(param)){
            result.setStatus(-1);
            result.setInfo("请添加参数");
            result.setSuccess(false);
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        InputStream inputStream  = null;
        String fileName = "";
        String path = "";
        try {
            MultipartFile file = multipartFile.getFile(param);
            fileName = file.getOriginalFilename();
            byte[] fileBuff = null;
            inputStream = file.getInputStream();
            if(inputStream!=null){
                int len1 = inputStream.available();
                fileBuff = new byte[len1];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            path = webServerUrl+res.get().toString();
            logger.debug("upload上传成功，路径："+path);
        }catch (Exception e){
            result.setSuccess(false);
            result.setInfo("上传异常："+e.getMessage());
            result.setStatus(-1);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            logger.error("file:"+fileName,e.fillInStackTrace());
            return result;
        }  finally {
            if (inputStream !=null){
                try {
                    inputStream.close();
                }catch (IOException io){
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    result.setSuccess(false);
                    result.setInfo("上传异常："+io.getMessage());
                    result.setStatus(-1);
                    logger.error(io.getMessage());
                    return result;
                }
            }
        }
        result.setSuccess(true);
        //图片地址
        result.setData(path);
        result.setStatus(0);
        response.setStatus(HttpServletResponse.SC_OK);
        return result;
    }


    @RequestMapping(value = "/upload1", method = RequestMethod.POST)
    @ResponseBody
    public  String upload1(@RequestParam("file") MultipartFile file) {
        String path = "";
        InputStream inputStream = null;
        byte[] fileBuff = null;
        if (!file.isEmpty()) {
            try {
                if(client == null) {
                    client = FastdfsClient.newBuilder()
                            .connectTimeout(connectTimeout)
                            .readTimeout(readTimeout)
                            .maxThreads(maxThreads)
                            .trackers(getTrackers())
                            .build();
                }
                String fileName = file.getOriginalFilename();
                inputStream = file.getInputStream();
                if(inputStream!=null){
                    int len = inputStream.available();
                    fileBuff = new byte[len];
                    inputStream.read(fileBuff);
                }
                //获取文件的扩展名
                String extension ="."+FilenameUtils.getExtension(fileName);
                if(".".equals(extension)){
                    extension =".jpg";
                }
                CompletableFuture<FileId> res = client.upload(extension, fileBuff);
                path = webServerUrl+res.get().toString();
                logger.debug("upload1上传成功,路径:"+path);
            }  catch (Exception e) {
                e.getStackTrace();
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                logger.error("上传失败："+e.getMessage());
                return "上传失败," + e.getMessage();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    logger.error("上传失败："+e.getMessage());
                    return "上传失败," + e.getMessage();
                }
            }
            response.setStatus(HttpServletResponse.SC_OK);
            return "上传成功,路径:"+path;
        } else {
            return "上传失败，因为文件是空的.";
        }
    }

    /**
     * 返回标准的result
     * @param file
     * @return
     */
    @RequestMapping(value = "/v2/upload1", method = RequestMethod.POST)
    @ResponseBody
    public  CommonResult upload1V2(@RequestParam("file") MultipartFile file) {
        CommonResult result = new CommonResult();
        String path = "";
        InputStream inputStream = null;
        byte[] fileBuff = null;
        if (!file.isEmpty()) {
            try {
                if(client == null) {
                    client = FastdfsClient.newBuilder()
                            .connectTimeout(connectTimeout)
                            .readTimeout(readTimeout)
                            .maxThreads(maxThreads)
                            .trackers(getTrackers())
                            .build();
                }
                String fileName = file.getOriginalFilename();
                inputStream = file.getInputStream();
                if(inputStream!=null){
                    int len = inputStream.available();
                    fileBuff = new byte[len];
                    inputStream.read(fileBuff);
                }
                //获取文件的扩展名
                String extension ="."+FilenameUtils.getExtension(fileName);
                if(".".equals(extension)){
                    extension =".jpg";
                }
                CompletableFuture<FileId> res = client.upload(extension, fileBuff);
                path = webServerUrl+res.get().toString();
                logger.debug("upload1上传成功,路径:"+path);
            }  catch (Exception e) {
                e.getStackTrace();
                logger.error("上传失败："+e.getMessage());
                result.setStatus(-1);
                result.setSuccess(false);
                result.setInfo("上传失败," + e.getMessage());
                return result;
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    result.setStatus(-1);
                    result.setSuccess(false);
                    result.setInfo("上传失败," + e.getMessage());
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    return result;
                }
            }
            response.setStatus(HttpServletResponse.SC_OK);
            result.setStatus(0);
            result.setSuccess(true);
            result.setInfo("上传成功");
            result.setData(path);
            return result;
        } else {
            return result;
        }
    }


    /**
     * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
     *
     * @param request
     * @return
     * @author gx
     * @create 2018年1月17日
     */
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public   @ResponseBody String batchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        String fileName = "";
        StringBuffer sb = new StringBuffer();
        String path = "";
        InputStream inputStream = null;
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            for (int i = 0; i < files.size(); ++i) {
                file = files.get(i);
                if (!file.isEmpty()) {
                    fileName = file.getOriginalFilename();
                    byte[] fileBuff = null;
                    inputStream = file.getInputStream();
                    if(inputStream!=null){
                        int len = inputStream.available();
                        fileBuff = new byte[len];
                        inputStream.read(fileBuff);
                    }
                    CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
                    path = webServerUrl+res.get().toString();
                    sb.append("文件："+fileName+"，上传路径："+path+"<br/>");
                } else {
                    return "You failed to upload " + i + " because the file was empty.";
                }
            }
        } catch (Exception e) {
            return "You failed to upload  => " + e.getMessage();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        return "upload successful<br/>"+sb.toString();
    }


    @RequestMapping(value = "/v2/upload/batch", method = RequestMethod.POST)
    public   @ResponseBody CommonResult batchUploadV2(HttpServletRequest request) {
        CommonResult result = new CommonResult();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        String fileName = "";
        StringBuffer sb = new StringBuffer();
        String path = "";
        InputStream inputStream = null;
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            for (int i = 0; i < files.size(); ++i) {
                file = files.get(i);
                if (!file.isEmpty()) {
                    fileName = file.getOriginalFilename();
                    byte[] fileBuff = null;
                    inputStream = file.getInputStream();
                    if(inputStream!=null){
                        int len1 = inputStream.available();
                        fileBuff = new byte[len1];
                        inputStream.read(fileBuff);
                    }
                    CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
                    path = webServerUrl+res.get().toString();
                    sb.append(fileName+":"+path+";");
                } else {
                    response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
                    result.setInfo("上传失败:the file was empty");
                    result.setStatus(-1);
                    result.setSuccess(false);
                    return result;
                }
            }
        } catch (Exception e) {
            result.setInfo("上传失败:"+e.getMessage());
            result.setStatus(-1);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setSuccess(false);
            return result;
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                result.setInfo("上传失败:"+e.getMessage());
                result.setStatus(-1);
                result.setSuccess(false);
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                logger.error("上传失败:"+e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setSuccess(true);
        result.setInfo("批量上传成功");
        result.setData(sb.toString());
        result.setStatus(0);
        return result;
    }


    /**
     * 读取网络图片，通过流上传
     * @param path
     * @return
     */
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public Result upload2(String path) {
        String filePath = "";
        Result result = new Result();
        InputStream inputStream = null;
        ByteArrayOutputStream bos = null;
        if (StringUtils.isBlank(path)) {
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("文件路径为空");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        try {
            if(client == null) {
                client = FastdfsClient.newBuilder()
                        .connectTimeout(connectTimeout)
                        .readTimeout(readTimeout)
                        .maxThreads(maxThreads)
                        .trackers(getTrackers())
                        .build();
            }
            //new一个URL对象
            URL url = new URL(path);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //超时响应时间为30秒
            conn.setConnectTimeout(30 * 1000);
            conn.setRequestProperty("Accept-Encoding", "identity");
            //通过输入流获取图片数据
            conn.connect();
            inputStream = conn.getInputStream();
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len= inputStream.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            byte[] dataImage = bos.toByteArray();
            CompletableFuture<FileId> res = client.upload(path, dataImage);
            filePath = webServerUrl+res.get().toString();
            logger.debug("upload2上传成功，路径："+filePath);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            logger.error(e.toString());
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        }finally {
            try {
                if(bos != null){
                    bos.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                logger.error("上传出现异常：" +e.toString());
                result.setState(-1);
                result.setSuccess(false);
                result.setMessage("上传出现异常：" + e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.addAttribute("filePath", filePath);
        result.setState(0);
        result.setSuccess(true);
        result.setMessage("上传成功");
        return result;
    }


    @RequestMapping(value = "/v2/upload2")
    @ResponseBody
    public CommonResult uploadV2(String path) {
        String filePath = "";
        CommonResult result = new CommonResult();
        InputStream inputStream = null;
        ByteArrayOutputStream bos = null;
        if (StringUtils.isBlank(path)) {
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("文件路径为空");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        try {
            if(client == null) {
                client = FastdfsClient.newBuilder()
                        .connectTimeout(connectTimeout)
                        .readTimeout(readTimeout)
                        .maxThreads(maxThreads)
                        .trackers(getTrackers())
                        .build();
            }
            //new一个URL对象
            URL url = new URL(path);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //超时响应时间为30秒
            conn.setConnectTimeout(30 * 1000);
            conn.setRequestProperty("Accept-Encoding", "identity");
            //通过输入流获取图片数据
            conn.connect();
            inputStream = conn.getInputStream();
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len= inputStream.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            byte[] dataImage = bos.toByteArray();
            CompletableFuture<FileId> res = client.upload(path, dataImage);
            filePath = webServerUrl+res.get().toString();
            logger.debug("upload2上传成功，路径："+filePath);
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (Exception e) {
            logger.error("上传出现异常：" +e.toString());
            result.setStatus(-1);
            result.setSuccess(false);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        }finally {
            try {
                if(bos != null){
                    bos.close();
                }
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error("上传出现异常：" + e.toString());
                result.setStatus(-1);
                result.setSuccess(false);
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setInfo("上传出现异常：" + e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setData(filePath);
        result.setStatus(0);
        result.setSuccess(true);
        result.setInfo("上传成功");
        return result;
    }

    @RequestMapping(value = "/v2/ftp/upload")
    @ResponseBody
    public  CommonResult ftpUploadFileV2(String path) {
        String filePath = "";
        FTPClient ftpClient = null;
        CommonResult result = new CommonResult();
        InputStream inputStream = null;
        if (StringUtils.isBlank(path)) {
            result.setStatus(-1);
            result.setSuccess(false);
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            result.setInfo("文件路径为空");
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            logger.debug("图片路径 : " + path);
            //通过输入流获取图片数据
            long startTime = System.currentTimeMillis();
            ftpClient = FtpUtils.getFtpClient(path);
            String remoteFileName = "";
            remoteFileName = path.substring(path.lastIndexOf("/") + 1);
            logger.debug("图片名称：" + remoteFileName);
            inputStream = ftpClient.retrieveFileStream(FtpUtils.encodingPath(remoteFileName));
            logger.debug("获取图片数据 SPEND TIME : " + StringUtils.formatDuring(System.currentTimeMillis() - startTime));
            String fileName = remoteFileName;
            byte[] fileBuff = null;
            if(inputStream!=null){
                int len = inputStream.available();
                fileBuff = new byte[len];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            filePath = webServerUrl+res.get().toString();
            logger.debug("/ftp/upload上传成功,路径："+filePath);
        } catch (Exception e) {
            result.setStatus(-1);
            result.setSuccess(false);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                    logger.debug("inputStream.close()关闭成功");
                    ftpClient.completePendingCommand();
                    logger.debug("ftpClient.completePendingCommand()关闭成功");
                } else {
                    result.setStatus(-1);
                    result.setSuccess(false);
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    result.setInfo("上传出现异常：服务器无资源或者图片路径不对或者无权限");
                    return result;
                }
            } catch (IOException e) {
                result.setStatus(-1);
                result.setSuccess(false);
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setInfo("上传出现异常：" + e.getMessage());
                return result;
            }
            FtpUtils.releaseFtpClient(ftpClient);
            logger.debug("releaseFtpClient关闭成功");
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setData(filePath);
        result.setStatus(0);
        result.setSuccess(true);
        result.setInfo("上传成功");
        return result;
    }

    @RequestMapping(value = "/ftp/upload")
    @ResponseBody
    public   Result ftpUploadFile(String path) {
        String filePath = "";
        FTPClient ftpClient = null;
        Result result = new Result();
        InputStream inputStream = null;
        if (StringUtils.isBlank(path)) {
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("文件路径为空");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            logger.debug("图片路径 : " + path);
            //通过输入流获取图片数据
            long startTime = System.currentTimeMillis();
            ftpClient = FtpUtils.getFtpClient(path);
            String remoteFileName = "";
            remoteFileName = path.substring(path.lastIndexOf("/") + 1);
            logger.debug("图片名称：" + remoteFileName);
            inputStream = ftpClient.retrieveFileStream(FtpUtils.encodingPath(remoteFileName));
            logger.debug("获取图片数据 SPEND TIME : " + StringUtils.formatDuring(System.currentTimeMillis() - startTime));
            String fileName = remoteFileName;
            byte[] fileBuff = null;
            if(inputStream!=null){
                int len = inputStream.available();
                fileBuff = new byte[len];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            filePath = webServerUrl+res.get().toString();
            logger.debug("/ftp/upload上传成功,路径："+filePath);
        } catch (Exception e) {
            result.setState(-1);
            result.setSuccess(false);
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                    logger.debug("inputStream.close()关闭成功");
                    ftpClient.completePendingCommand();
                    logger.debug("ftpClient.completePendingCommand()关闭成功");
                } else {
                    result.setState(-1);
                    result.setSuccess(false);
                    response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                    result.setMessage("上传出现异常：服务器无资源或者图片路径不对或者无权限");
                    return result;
                }
            } catch (IOException e) {
                result.setState(-1);
                result.setSuccess(false);
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setMessage("上传出现异常：" + e.getMessage());
                return result;
            }
            FtpUtils.releaseFtpClient(ftpClient);
            logger.debug("releaseFtpClient关闭成功");
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.addAttribute("filePath", filePath);
        result.setState(0);
        result.setSuccess(true);
        result.setMessage("上传成功");
        return result;
    }

    @RequestMapping(value = "/v2/sftp/upload")
    @ResponseBody
    public   CommonResult sftpUploadFileV2(String path) {
        String filePath = "";
        CommonResult result = new CommonResult();
        InputStream inputStream = null;
        if (StringUtils.isBlank(path)) {
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("文件路径为空");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            //通过输入流获取图片数据
            String host = sftpConfigProperties.getHost();
            int port = sftpConfigProperties.getPort();
            String usename = sftpConfigProperties.getUsername();
            String password = sftpConfigProperties.getPassword();
            SFTPUtils.connectServer(host,port,usename,password);
            inputStream = SFTPUtils.readFile(path);
            String fileName = path.substring(path.lastIndexOf("/")+1);
            byte[] fileBuff = null;
            if(inputStream!=null){
                int len = inputStream.available();
                fileBuff = new byte[len];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            filePath = webServerUrl+res.get().toString();
            logger.debug("/sftp/upload上传成功,路径："+filePath);
        } catch (IOException e) {
            logger.error("上传出现异常：" +e.toString());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        }  catch (JSchException e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            logger.error("上传出现异常：" +e.toString());
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        } catch (InterruptedException e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            logger.error("上传出现异常：" +e.toString());
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        } catch (ExecutionException e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            logger.error("上传出现异常：" +e.toString());
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("上传出现异常：" + e.getMessage());
            return result;
        } finally {
            try {
                if(inputStream !=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                logger.error("上传出现异常：" +e.toString());
                result.setStatus(-1);
                result.setSuccess(false);
                result.setInfo("上传出现异常：" + e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setData(filePath);
        result.setStatus(0);
        result.setSuccess(true);
        result.setInfo("上传成功");
        return result;
    }


    @RequestMapping(value = "/sftp/upload")
    @ResponseBody
    public   Result sftpUploadFile(String path) {
        String filePath = "";
        Result result = new Result();
        InputStream inputStream = null;
        if (StringUtils.isBlank(path)) {
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("文件路径为空");
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return result;
        }
        if(client == null) {
            client = FastdfsClient.newBuilder()
                    .connectTimeout(connectTimeout)
                    .readTimeout(readTimeout)
                    .maxThreads(maxThreads)
                    .trackers(getTrackers())
                    .build();
        }
        try {
            //通过输入流获取图片数据
            String host = sftpConfigProperties.getHost();
            int port = sftpConfigProperties.getPort();
            String usename = sftpConfigProperties.getUsername();
            String password = sftpConfigProperties.getPassword();
            SFTPUtils.connectServer(host,port,usename,password);
            inputStream = SFTPUtils.readFile(path);
            String fileName = path.substring(path.lastIndexOf("/")+1);
            byte[] fileBuff = null;
            if(inputStream!=null){
                int len1 = inputStream.available();
                fileBuff = new byte[len1];
                inputStream.read(fileBuff);
            }
            CompletableFuture<FileId> res = client.upload(fileName, fileBuff);
            filePath = webServerUrl+res.get().toString();
            logger.debug("/sftp/upload上传成功,路径："+filePath);
        } catch (IOException e) {
            logger.error("上传出现异常：" +e.toString());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        }  catch (JSchException e) {
            logger.error("上传出现异常：" +e.toString());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        } catch (InterruptedException e) {
            logger.error("上传出现异常：" +e.toString());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        } catch (ExecutionException e) {
            logger.error("上传出现异常：" +e.toString());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("上传出现异常：" + e.getMessage());
            return result;
        } finally {
            try {
                if(inputStream !=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error("上传出现异常：" +e.toString());
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setState(-1);
                result.setSuccess(false);
                result.setMessage("上传出现异常：" + e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.addAttribute("filePath", filePath);
        result.setState(0);
        result.setSuccess(true);
        result.setMessage("上传成功");
        return result;
    }

    @RequestMapping("/downloadtest")
    public void download(String apiUrl,String path,String keyCode) throws Exception {
        String stFile= UUID.randomUUID().toString()+".png";
        // 构造URL
        String dUrl = apiUrl+"/file/v2/download?keyCode="+keyCode+"&path="+path+"&fileName=test.png";

        URL url = new URL(dUrl);

        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();

        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File("C:\\Users\\Army\\Desktop");
        if(!sf.exists()){
            sf.mkdirs();
        }
        String saveFilePath = sf.getPath()+File.separator +stFile;
        OutputStream os = new FileOutputStream(saveFilePath);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }

    /**
     * 下载到任意路径
     * @param path
     * @param fileName
     * @param response
     * @return
     */
    @RequestMapping(value = "/download",produces="text/plain;charset=UTF-8")
    @ResponseBody
    public  Result download(String path,String fileName, HttpServletResponse response) {
        Result result = new Result();
        OutputStream out = null;
        try {
            if(StringUtils.isBlank(path)){
                result.setState(-1);
                result.setSuccess(false);
                result.setMessage("文件路径为空");
                response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
                return result;
            }
            if(StringUtils.isBlank(fileName)){
                result.setState(-1);
                result.setSuccess(false);
                result.setMessage("文件名为空");
                response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
                return result;
            }
            // 清空response
            response.reset();
            //设置响应头，控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes()));
            //读取要下载的文件，保存到文件输入流
            int index = path.indexOf("group");
            String relativePath = path.substring(index+7);
            String group = path.substring(index,index+6);
            FileId fileId = new FileId(group,relativePath);
            CompletableFuture<byte[]> download = client.download(fileId);
            byte[] bytes = download.get();
            //创建输出流
            out = response.getOutputStream();
            out.write(bytes);
        } catch (Exception e) {
            logger.error("下载失败："+e.getMessage());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setState(-1);
            result.setSuccess(false);
            result.setMessage("下载出现异常："+e.getMessage());
            return result;
        }finally {
            //关闭
            try {
                out.close();
            } catch (IOException e) {
                logger.error("下载失败："+e.getMessage());
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setState(-1);
                result.setSuccess(false);
                result.setMessage("下载出现异常："+e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setState(0);
        result.setSuccess(true);
        result.setMessage("下载成功");
        return result;
    }

    @RequestMapping(value = "/v2/download",produces="text/plain;charset=UTF-8")
    @ResponseBody
    public  CommonResult downloadV2(String path,String fileName, HttpServletResponse response) {
        CommonResult result = new CommonResult();
        OutputStream out = null;
        try {
            if(StringUtils.isBlank(path)){
                result.setStatus(-1);
                result.setSuccess(false);
                result.setInfo("文件路径为空");
                response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
                return result;
            }
            if(StringUtils.isBlank(fileName)){
                result.setStatus(-1);
                result.setSuccess(false);
                result.setInfo("文件名为空");
                response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
                return result;
            }
            // 清空response
            response.reset();
            //设置响应头，控制浏览器下载该文件
            response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes()));
            //读取要下载的文件，保存到文件输入流
            int index = path.indexOf("group");
            String relativePath = path.substring(index+7);
            String group = path.substring(index,index+6);
            FileId fileId = new FileId(group,relativePath);
            CompletableFuture<byte[]> download = client.download(fileId);
            byte[] bytes = download.get();
            //创建输出流
            out = response.getOutputStream();
            out.write(bytes);
        } catch (Exception e) {
            logger.error("下载失败："+e.getMessage());
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            result.setStatus(-1);
            result.setSuccess(false);
            result.setInfo("下载出现异常："+e.getMessage());
            return result;
        }finally {
            //关闭
            try {
                out.close();
            } catch (IOException e) {
                logger.error("下载失败："+e.getMessage());
                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
                result.setStatus(-1);
                result.setSuccess(false);
                result.setInfo("下载出现异常："+e.getMessage());
                return result;
            }
        }
        response.setStatus(HttpServletResponse.SC_OK);
        result.setStatus(0);
        result.setSuccess(true);
        result.setInfo("下载成功");
        return result;
    }
}
